package util.db;



import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;

import model.db.Query;
import model.db.Vertical;
import model.db.VerticalResult;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import contact.util.HibernateUtil;

import util.io.FileInput;


public class FeedDatabase {
	/**
	 * @param args
	 */
	
	static final int query_pos=0;
	static final int vertical_pos=1;
	static final int title_pos=2;
	static final int snippet_pos=3;
	static final int url_pos=4;
	static final int thumbnail_pos=5;
	
	public static Hashtable<String, Query> getQueryInfo() {

		Hashtable<String, Query> h = new Hashtable<String, Query>();
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Query> queries = null;
		try {

			queries = (List<Query>) session.createQuery("from Query").list();

		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();

		for (int i = 0; i < queries.size(); i++) {
			Query q = queries.get(i);
			System.out.println("Reading " + q.getQuery());
			h.put(q.getQuery(), q);

		}
	//	session.close();
		return h;

	}
	
	public static void feedWebResults(String path){
		
		Hashtable<String, Query> query_info = getQueryInfo();
		Hashtable<String, Vertical> vertical_info = getVerticalInfo();
		
		
	
		FileInput in = new FileInput(path);
	
		SessionFactory sessionFactory = new org.hibernate.cfg.AnnotationConfiguration().configure().buildSessionFactory();
		Session session = null;
		session =sessionFactory.openSession();
	    session.beginTransaction();
		String line = in.readString();
		String current_query="";
		String current_vertical="";
		int rank=0;
		
		while(line!=null){
			
			String t[] = line.split("\t");
			
			String query = t[query_pos];
			String vertical = t[vertical_pos];
			
			if(query.equals(current_query)  && vertical.equals(current_vertical)){
				
				rank++;
			}else{
				
				rank=1;
			}
			
			current_query=query;
			
			current_vertical=vertical;
			
			String title = "";
			
			
			if(t.length>=title_pos+1){
				title= t[title_pos];
			}
			
			String snippet ="";
			
			if(t.length>=snippet_pos+1){
				snippet= t[snippet_pos];
			}
			
			
			String url ="";
			
			if(t.length>=url_pos+1){
				url= t[url_pos];
			}
			
			String thumbnail= "";
			
			if(t.length>=thumbnail_pos+1){
				thumbnail= t[thumbnail_pos];
			}
			
			line =in.readString();
			
			VerticalResult v = new VerticalResult();
			
			if(!query_info.containsKey(query)){
				System.out.println("QUERY: " + query + "\t not found-------------------------------------------") ;
				
				continue;
				
			}
			v.setQuery_id(query_info.get(query).getId());
			v.setVertical_id(vertical_info.get(vertical).getId());
			
			v.setTitle(title);
			v.setSnippet(snippet);
			v.setThumbnail(thumbnail);
			v.setUrl(url);
			
			v.setRank(rank);
		
			
			System.out.println("Adding webresult:" +  vertical + "\t"+ query + "\t" + title + "\t"  +url + "\t"+ rank);
			session.save(v);
			}
			
			
		
	session.getTransaction().commit();
	session.flush();
	session.close();
		
		
	}
	
	public static Hashtable<String, Vertical> getVerticalInfo() {

		Hashtable<String, Vertical> h = new Hashtable<String, Vertical>();
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Vertical> queries = null;
		try {

			queries = (List<Vertical>) session.createQuery("from Vertical").list();

		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();

		for (int i = 0; i < queries.size(); i++) {
			Vertical q = queries.get(i);
			h.put(q.getCode(), q);
			System.out.println("Reading " + q.getCode());

		}
		//session.close();
		return h;

	}
	
	
	
	
	public static void feedQueries(String path){
		HashSet<String> set = new HashSet<String>();
		Session session = null;
		FileInput in = new FileInput(path);
		
		SessionFactory sessionFactory = new org.hibernate.cfg.AnnotationConfiguration().configure().buildSessionFactory();
	    session =sessionFactory.openSession();
	    session.beginTransaction();
		String line = in.readString();
		
		while(line!=null){
			
			String t[] = line.split("\t");
			
			line =in.readString();
			
			Query q = new Query();
			
			q.setQuery(t[query_pos]);
			q.setDescription("");
			q.setAge("kids");
			q.setType("kids");
			
			if(!set.contains(q.getQuery())){
				System.out.println("Adding query " + q.getQuery());
				set.add(q.getQuery());
				session.save(q);
			  
			}
			
			
		}
	session.getTransaction().commit();
	session.flush();
	session.close();

	}
	
	
	public static void feedVerticals(String path){
		
		Session session = null;
		FileInput in = new FileInput(path);
		
		SessionFactory sessionFactory = new org.hibernate.cfg.AnnotationConfiguration().configure().buildSessionFactory();
	    session =sessionFactory.openSession();
	    session.beginTransaction();
		String line = in.readString();
		
		while(line!=null){
			
			String t[] = line.split("\t");
			String code=t[0];
			String name=t[1];
			String description = t[2];
			String url = t[3];
			line =in.readString();
			
			Vertical v = new Vertical();
			
			v.setDescription(description);
			v.setName(name);
			v.setCode(code);
			v.setUrl(url);
	
			session.save(v);
			
			
		}
	session.getTransaction().commit();
	session.flush();
	session.close();
		  
	
	}
	
	public static void main(String[] args) {
		
		String path="/Users/sergioduarte/projects/data/snippet_output/test_verticals/test_web_results_complete.txt";
		String path_verticals="/Users/sergioduarte/projects/data/verticals/vertical_description.txt";
		
		
		path = "/home/sergio/data/snippets/snippets_clean.txt";
		//feedQueries(path);
		
		//getQueryInfo();
		feedWebResults(path);
		//feedVerticals(path_verticals);
		
	}

}
